//
//  NetworkTools.swift
//  Sina
//
//  Created by 邹志华 on 15/11/8.
//  Copyright © 2015年 zzh. All rights reserved.
//

import UIKit
import AFNetworking


class NetworkTools: AFHTTPSessionManager {
    
    //创建单例
    static let sharedInstance: NetworkTools = {
        
        //请求授权
        //api.weibo.com/oauth2/authorize

        
        let urlString = "https://api.weibo.com/"

        let tool = NetworkTools(baseURL: NSURL(string: urlString))
//        set
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    
    /* 	必选	类型及范围	说明
    client_id	true	string	申请应用时分配的AppKey。
    client_secret	true	string	申请应用时分配的AppSecret。
    grant_type	true	string	请求的类型，填写authorization_code
    
    grant_type为authorization_code时
    必选	类型及范围	说明
    code	true	string	调用authorize获得的code值。
    redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
*/
    
    //MARK: - OAtuh授权
    private let client_id = "1700792831"
    let redirect_uri = "http://weibo.com/jiushixiaoyan/"
    private let client_secret = "fc8e377522cac10147365a6a5e30818f"
    let grant_type = "authorization_code"
    //OAthURL地址
    
    
    func oauthRUL() -> NSURL{
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    
    
    //https://api.weibo.com/oauth2/access_token

    
    ///使用闭包回调
    //MARK: - 加载AccessToken
    ///加载AccessToken
    
    func loadAccessToken(code:String ,finshed:(result:[String:AnyObject]?,error:NSError?) -> ()) {
     
        
        let urlStirng = "oauth2/access_token"
        //参数
        
        let parameters = [
            "client_id":  client_id,
            "client_secret": client_secret,
            "grant_type":  grant_type,
            "code":code,
            "redirect_uri": redirect_uri,
        ]
        
        
//        responseSerializer = AFHTTPResponseSerializer()
        
        //result : 请求结构
        POST(urlStirng, parameters: parameters, success: { (_, result) -> Void in
            //请求成功
//            let data = String(data:result as!NSData,encoding: NSUTF8StringEncoding)
//            print("data:\(data)")
//            
             finshed(result:result as? [String: AnyObject], error: nil)
            
            }) { (_, error:NSError) -> Void in
                //请求失败
                finshed(result: nil, error: error)
        }//
        
    }
    
    
}
